package com.diancan.modules.order;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.diancan.common.Result;
import com.diancan.domain.*;
import com.diancan.modules.good.GoodService;
import com.diancan.modules.order.order_details.OrderDetailsService;
import com.diancan.modules.admin.restaurant.RestaurantService;
import com.diancan.modules.user.user.UserService;
import com.diancan.utils.OrdersUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("orders")
@CrossOrigin
public class OrderController {
    private final OrderService orderService;
    private final UserService userService;
    private final OrderDetailsService orderDetailsService;
    private final RestaurantService restaurantService;
    private final GoodService goodService;

    public OrderController(OrderService buyService, UserService userService, OrderDetailsService orderDetailsService, RestaurantService restaurantService, GoodService goodService) {
        this.orderService = buyService;
        this.userService = userService;
        this.orderDetailsService = orderDetailsService;
        this.restaurantService = restaurantService;
        this.goodService = goodService;
    }

    /**
     * 创建订单
     *
     * @param map userId,tableId,goodArrayList
     * @return
     */
    @PostMapping("createOrder")
    public Result createOrder(@RequestBody Map map) {
        JSONObject jsonObject = new JSONObject(map);
        String userId = (String) jsonObject.get("userId");
        Integer tableId = Integer.valueOf((String) jsonObject.get("tableId"));
        ArrayList<LinkedHashMap> linkedHashMaps = (ArrayList<LinkedHashMap>) jsonObject.get("goods");
        ArrayList<Good> goodArrayList = new ArrayList<>();
        for (LinkedHashMap l : linkedHashMaps) {
            goodArrayList.add(JSONObject.parseObject(new JSONObject(l).toString(), Good.class));
        }

        // 创建订单和订单详细信息
        Orders order = new Orders();
        ArrayList<OrderDetails> orderDetailsArrayList = new ArrayList<>();
        String orderId = OrdersUtils.createOrderId();

        order.setUserId(userId);
        order.setId(orderId);
        order.setTableId(tableId);
        order.setAmount(new BigDecimal("0.00"));
        for (Good g : goodArrayList) {
            if (g.getCount() > 0) {
                order.setAmount(order.getAmount().add(g.getPrice().multiply(new BigDecimal(g.getCount()))));
                OrderDetails orderDetail = new OrderDetails();
                orderDetail.setOrderId(orderId);
                orderDetail.setCount(g.getCount());
                orderDetail.setGoodId(g.getId());
                orderDetailsArrayList.add(orderDetail);
            }
        }
        orderService.save(order);
        orderDetailsService.saveBatch(orderDetailsArrayList);

        // 返回订单信息
        return Result.buildSuccessResult(orderService.getById(orderId));
    }

    /**
     * 付款
     *
     * @param map 订单编号
     * @return
     */
    @PostMapping("pay")
    @Transactional
    public Result fk(@RequestBody Map map) {
        JSONObject jsonObject = new JSONObject(map);
        String orderId = (String) jsonObject.get("orderId");
        Orders order = orderService.getById(orderId);
        if (order == null) {
            return Result.buildFailureResult(401, "订单不存在", null);
        }
        User user = userService.getById(order.getUserId());
        Restaurant restaurant = restaurantService.list().get(0);

        user.setBalance(user.getBalance().subtract(order.getAmount()));
        if (user.getBalance().doubleValue() < 0) {
            return Result.buildFailureResult(402, "余额不足", null);
        }
        restaurant.setBalance(restaurant.getBalance().add(order.getAmount()));
        if (userService.updateById(user) && restaurantService.updateById(restaurant)) {
            order.setState("已付款");
            if (orderService.updateById(order)) {
                return Result.buildSuccessResult("支付成功");
            } else {
                return Result.buildFailureResult(500, "系统错误", null);
            }
        } else {
            return Result.buildFailureResult(500, "系统错误", null);
        }
    }

    /**
     * 获取最近订单及订单详细信息
     *
     * @param userId 用户id
     * @return
     */
    @GetMapping("getOrderAndDetails")
    public Result getOrderAndDetails(String userId) {
        if (userId == null) {
            return Result.buildFailureResult("userId为空");
        }

        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).orderByDesc("id");
        ArrayList<Orders> ordersArrayList = (ArrayList<Orders>) orderService.list(wrapper);
        if (ordersArrayList == null) {
            return Result.buildSuccessResult(null);
        } else {
            Orders order = ordersArrayList.get(0);
            QueryWrapper<OrderDetails> wrapper1 = new QueryWrapper<>();
            wrapper1.eq("order_id", order.getId());
            ArrayList<OrderDetails> orderDetailsArrayList = (ArrayList<OrderDetails>) orderDetailsService.list();
            ArrayList<Good> goodArrayList = new ArrayList<>();
            for (OrderDetails o : orderDetailsArrayList) {
                Good good = goodService.getById(o.getGoodId());
                good.setCount(o.getCount());
                goodArrayList.add(good);
            }

            Map<String, Object> map = new HashMap<>();
            map.put("order", order);
            map.put("orderDetails", goodArrayList);
            return Result.buildSuccessResult(map);
        }
    }

    // 获取全部订单
    @GetMapping("getOrders")
    public Result getOrders(String userId) {
        if (userId == null) {
            return Result.buildFailureResult("userId为空");
        }

        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).orderByDesc("id").ne("state","已取消");
        ArrayList<Orders> ordersArrayList = (ArrayList<Orders>) orderService.list(wrapper);

        return Result.buildSuccessResult(ordersArrayList);
    }

    // 获取待付款订单
    @GetMapping("getOrdersDfk")
    public Result getOrdersDfk(String userId) {
        if (userId == null) {
            return Result.buildFailureResult("userId为空");
        }

        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).orderByDesc("id").eq("state", "待付款");
        ArrayList<Orders> ordersArrayList = (ArrayList<Orders>) orderService.list(wrapper);

        return Result.buildSuccessResult(ordersArrayList);
    }

    // 获取已付款订单
    @GetMapping("getOrdersYfk")
    public Result getOrdersYfk(String userId) {
        if (userId == null) {
            return Result.buildFailureResult("userId为空");
        }

        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).orderByDesc("id").eq("state", "已付款");
        ArrayList<Orders> ordersArrayList = (ArrayList<Orders>) orderService.list(wrapper);

        return Result.buildSuccessResult(ordersArrayList);
    }

    // 获取已完成订单
    @GetMapping("getOrdersYwc")
    public Result getOrdersYwc(String userId) {
        if (userId == null) {
            return Result.buildFailureResult("userId为空");
        }

        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).orderByDesc("id").eq("state", "已完成");
        ArrayList<Orders> ordersArrayList = (ArrayList<Orders>) orderService.list(wrapper);

        return Result.buildSuccessResult(ordersArrayList);
    }

    // 获取待付款和已付款订单
    @GetMapping("getOrdersDfkAndYfk")
    public Result getOrdersDfkAndYfk(String userId) {
        if (userId == null) {
            return Result.buildFailureResult("userId为空");
        }

        QueryWrapper<Orders> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userId).orderByDesc("id").eq("state", "已付款").or().eq("state", "待付款");
        ArrayList<Orders> ordersArrayList = (ArrayList<Orders>) orderService.list(wrapper);

        return Result.buildSuccessResult(ordersArrayList.get(0));
    }

    // 根据订单id获取订单详情
    @GetMapping("getOrderDetail")
    public Result getOrdetrDetail(String id) {
        QueryWrapper<OrderDetails> wrapper = new QueryWrapper<>();
        wrapper.eq("order_id", id);
        ArrayList<Good> goods = (ArrayList<Good>) goodService.list();
        ArrayList<OrderDetails> orderDetails = (ArrayList<OrderDetails>) orderDetailsService.list(wrapper);
        for (OrderDetails o : orderDetails) {
            for (Good g:goods){
                if (o.getGoodId().equals(g.getId())){
                    g.setCount(o.getCount());
                }
            }
        }
        ArrayList<Good> reGoods = new ArrayList<>();
        for (Good g:goods){
            if (g.getCount() > 0){
                reGoods.add(g);
            }
        }
        return Result.buildSuccessResult(reGoods);
    }

    // 根据id获取订单
    @GetMapping("getOrderById")
    public Result getOrderById(String id) {
        return Result.buildSuccessResult(orderService.getById(id));
    }
}
